<template>
  <view class="payment-methods">
    <view class="section-title">{{ title || $t('comm.paymentMethods') }}</view>
    
    <view v-if="isLoading" class="loading-container">
      <uni-load-more status="loading" loading-text="加载中..." />
    </view>
    
    <view v-else-if="paymentMethods.length === 0" class="empty-container">
      <text>{{ emptyText || $t('comm.noPaymentMethods') }}</text>
    </view>
    
    <view v-else>
      <view class="method-item" 
            v-for="(method, index) in paymentMethods" 
            :key="method.paymentMethodNo || index" 
            @click="selectPaymentMethod(index)" 
            :class="{ 'selected': selectedMethod === index }">
        <view class="method-icon">
          <image :src="method.iconUrl || '/static/default_setting.png'" mode="aspectFit" style="width: 24px; height: 24px;"></image>
        </view>
        <view class="method-name">{{ method.methodName }}</view>
        <view class="method-select">
          <image src="/static/checked.png" mode="aspectFit" style="width: 25px; height: 25px;" v-if="selectedMethod === index"></image>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  name: 'PaymentMethods',
  props: {
    // 套餐详情，用于添加兑换支付方式
    packageDetails: {
      type: Object,
      default: () => ({})
    },
    // 初始选中的支付方式索引
    initialSelectedIndex: {
      type: Number,
      default: 0
    },
    // 是否自动加载支付方式
    autoLoad: {
      type: Boolean,
      default: true
    },
    // 自定义标题
    title: {
      type: String,
      default: ''
    },
    // 无支付方式时的提示文本
    emptyText: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      // 支付方式列表
      paymentMethods: [],
      // 选中的支付方式索引
      selectedMethod: 0,
      // 加载状态
      isLoading: false,
      // 兑换类型列表
      exchangeTypes: ['prepaid', 'gameCoin', 'amusementCoin', 'lotteryEle', 'lottery', 'point'],
      // 兑换类型配置映射
      exchangeConfig: {
          prepaid: { field: 'prepaidExchange', unit: this.$t('comm.str1'), icon: '/static/yucunkuan.png', channel: 'PREPAID_EXCHANGE' },
          gameCoin: { field: 'gameCoinExchange', unit: this.$t('comm.str2'), icon: '/static/youxibi.png', channel: 'GAME_COIN_EXCHANGE' },
          amusementCoin: { field: 'amusementCoinExchange', unit: this.$t('comm.str3'), icon: '/static/youlebi.png', channel: 'AMUSEMENT_COIN_EXCHANGE' },
          lotteryEle: { field: 'lotteryEleExchange', unit: this.$t('comm.str5'), icon: '/static/electronic-lottery.png', channel: 'LOTTERY_EXCHANGE' },
          lottery: { field: 'lotteryExchange', unit: this.$t('comm.str4'), icon: '/static/lottery.png', channel: 'LOTTERY_EXCHANGE' },
          point: { field: 'pointsExchange', unit: this.$t('comm.str6'), icon: '/static/points.png', channel: 'POINTS_EXCHANGE' }
        }
    };
  },
  computed: {
    // 获取当前选中的支付方式
    currentPaymentMethod() {
      if (this.paymentMethods.length === 0 || this.selectedMethod >= this.paymentMethods.length) {
        return null;
      }
      return this.paymentMethods[this.selectedMethod];
    },
    // 判断当前选中的是否为兑换方式
    isCurrentMethodExchange() {
      return this.currentPaymentMethod && this.exchangeTypes.includes(this.currentPaymentMethod.paymentMethodNo);
    }
  },
  watch: {
    // 监听套餐详情变化，更新兑换支付方式
    packageDetails: {
      handler(newVal) {
        if (newVal && this.paymentMethods.length > 0) {
          this.updateExchangePaymentMethods(newVal);
        }
      },
      deep: true
    },
    // 监听选中的支付方式变化，通知父组件
    selectedMethod(newVal) {
      this.$emit('select-change', {
        index: newVal,
        method: this.currentPaymentMethod,
        isExchange: this.isCurrentMethodExchange
      });
    }
  },
  mounted() {
    // 初始化选中索引
    this.selectedMethod = this.initialSelectedIndex;
    
    // 如果设置了自动加载，则加载支付方式
    if (this.autoLoad) {
      this.loadPaymentMethods();
    }
  },
  methods: {
    // 加载支付方式列表
    async loadPaymentMethods() {
		return;//todo 临时拦截
      try {
        this.isLoading = true;
        const response = await this.$http.post('/paymentMethod/list/paymentMethod');
        this.paymentMethods = response || [];
        
        // 如果提供了套餐详情且支持兑换，添加兑换支付方式
        if (this.packageDetails && this.packageDetails.allowExchange === 1) {
          this.addExchangePaymentMethods(this.packageDetails);
        }
        
        // 确保选中索引有效
        if (this.selectedMethod >= this.paymentMethods.length) {
          this.selectedMethod = 0;
        }
        
        // 通知父组件加载完成
        this.$emit('load-complete', this.paymentMethods);
      } catch (error) {
        console.error('获取支付方式失败:', error);
        this.$emit('load-error', error);
        // 可以通过props配置是否显示错误提示
      } finally {
        this.isLoading = false;
      }
    },
    
    // 添加兑换支付方式
    addExchangePaymentMethods(packageDetails) {
      // 清空现有的兑换支付方式
      this.removeExchangePaymentMethods();
      
      // 使用配置映射循环添加所有兑换支付方式
      for (const [type, config] of Object.entries(this.exchangeConfig)) {
        const exchangeValue = packageDetails[config.field];
        if (exchangeValue && exchangeValue > 0) {
          this.paymentMethods.push({
            methodName: `${config.unit}兑换(${exchangeValue})`,
            paymentMethodNo: type,
            channelCode: config.channel,
            iconUrl: config.icon
          });
        }
      }
    },
    
    // 更新兑换支付方式
    updateExchangePaymentMethods(packageDetails) {
      this.addExchangePaymentMethods(packageDetails);
    },
    
    // 移除所有兑换支付方式
    removeExchangePaymentMethods() {
      this.paymentMethods = this.paymentMethods.filter(method => 
        !this.exchangeTypes.includes(method.paymentMethodNo)
      );
    },
    
    // 选择支付方式
    selectPaymentMethod(index) {
      if (index >= 0 && index < this.paymentMethods.length) {
        this.selectedMethod = index;
      }
    },
    
    // 手动设置选中的支付方式
    setSelectedMethod(index) {
      this.selectPaymentMethod(index);
    },
    
    // 获取所有支付方式
    getAllPaymentMethods() {
      return this.paymentMethods;
    },
    
    // 根据支付方式编号查找支付方式
    findPaymentMethodByNo(paymentMethodNo) {
      return this.paymentMethods.find(method => method.paymentMethodNo === paymentMethodNo);
    },
    
    // 刷新支付方式列表
    refreshPaymentMethods() {
      this.loadPaymentMethods();
    }
  }
};
</script>

<style scoped>
.payment-methods {
  background-color: #fff;
  margin-top: 10px;
  padding: 16px;
}

.section-title {
  font-size: 14px;
  color: #999;
  margin-bottom: 10px;
}

.method-item {
  display: flex;
  align-items: center;
  height: 50px;
  border-bottom: 1px solid #eee;
  transition: background-color 0.2s;
  justify-content: space-between;
}

.method-item.selected {
  background-color: #f0f8ff;
}

.method-item.selected .method-name {
  color: #1677FF;
  font-weight: 500;
}

.method-item:last-child {
  border-bottom: none;
}

.method-icon {
  width: 30px;
  margin-right: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.loading-container {
  padding: 20px 0;
  display: flex;
  justify-content: center;
}

.empty-container {
  padding: 20px 0;
  text-align: center;
  color: #999;
  font-size: 14px;
}

.method-name {
  flex: 1;
  font-size: 15px;
  color: #333;
}

.method-select {
  width: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-left: 10rpx;
}
</style>